/*******************************************************************************

  Paying Outsourced Labor: Direct Evidence from Linked Temp Agency-Worker-Client Data

  By Andres Drenik, Simon Jäger, Pascuel Plotkin and Benjamin Schoefer
	January 7th, 2021

	DESCRIPTION: Creates Dataset that Contains Regular Worker Tenure by Firm

*******************************************************************************/




/********************************************************************************
***** Preliminaries
********************************************************************************/
set more off
cap log close
local curr_date = c(current_date)
log using "${logs}/08_Reg_Tenure`curr_date'", replace


/********************************************************************************
***** Load Clean Dataset
********************************************************************************/

use "${intermediate_data_emp}/full_Dataset_Clean.dta", clear

********

** Generate spells for Regular Workers

	*Drop all Temp Workers
	drop if temp_worker == 1

	*Define data as time series
	gegen workerjobmatch = group(cuil_trab cuit_empl real_firm)
	drop if workerjobmatch == .
	xtset workerjobmatch date

  	*Measure spells
	tsspell workerjobmatch
	gen start_date = date if _seq == 1
	gen end_date = date if _end == 1

	*Generate a variable for the tenure
	bys workerjobmatch _spell: gen tenure = _seq[_N]

	*Average tenure by spell
	gcollapse (mean) tenure cuit_empl, by(workerjobmatch _spell)

	*Average tenure by firm
	gcollapse (mean) tenure, by(cuit_empl)

	rename cuit_empl cuit_reg3
	save "${intermediate_data_emp}/reg_tenure.dta", replace

log close
